package com.anrongtec.zcpt.openapi;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.base.BaseActivity;
import com.anrongtec.zcpt.callback.DoubleClickListener;
import com.anrongtec.zcpt.callback.StoreStringCallBack;
import com.anrongtec.zcpt.constant.AuthCode;
import com.anrongtec.zcpt.interfaces.HttpUtil;
import com.anrongtec.zcpt.interfaces.URLConstants;
import com.anrongtec.zcpt.interfaces.module.JsonDataRestult;
import com.anrongtec.zcpt.openapi.constant.Constant;
import com.anrongtec.zcpt.openapi.interfaces.ShuJuInterface;
import com.anrongtec.zcpt.openapi.manager.IAuthCallBack;
import com.anrongtec.zcpt.openapi.manager.OperationCallBack;
import com.anrongtec.zcpt.openapi.manager.UAManager;
import com.anrongtec.zcpt.openapi.model.AccessTokenInfo;
import com.anrongtec.zcpt.openapi.model.JsonDataResult;
import com.anrongtec.zcpt.openapi.model.Staff;
import com.anrongtec.zcpt.openapi.util.GsonUtil;
import com.anrongtec.zcpt.util.LogUtil;
import com.art.base.util.DialogUtil;
import com.art.base.util.NetUtil;
import com.art.base.util.PreferenceUtils;
import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.OkHttpUtils;

import okhttp3.Request;
import okhttp3.Response;

/**
 * 安荣第三方登陆
 */
public class ARTAuthActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "ARTAuthActivity";
    private Button btn_login;//登陆
    private Button btn_user_logout;//登出
    private String type = "0";//登陆类型
    private String mAccessToken;
    private TextView tv_login_user_name;//用户名
    private TextView tv_login_user_id;//身份证
    private TextView tv_title_right;
    private ShuJuInterface mJuInterface;
    private LinearLayout ll_login_user;//已登录用户
    private String mUserString;
    private ProgressDialog proDialog;
    private ProgressDialog appAuthDialog;
    private ProgressDialog mLogoutDialog;
    private boolean isSwitcher;//是否切换用户
    private AccessTokenInfo mTokenInfo;

    private String mAppkey;
    private String mPackageName;
    private ImageView iv_no_network;
    private RelativeLayout rl_no_network;
    private ProgressDialog mLoadingDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleShow(false);
        setContentView(R.layout.activity_anrong_login);
        PreferenceUtils.init(getApplication());
        PreferenceUtils.getInstance().save(Constant.PREFERENCE.MISFROMTHIRD, true);
        mJuInterface = new ShuJuInterface(this);
        getIntentData();
        initOkhttp();
        initView();
        initEvent();
        toAppAuthLogin();
    }

    @Override
    protected void onCreateCustomToolBar(Toolbar toolbar) {
        super.onCreateCustomToolBar(toolbar);
    }

    private void initOkhttp() {
        OkHttpUtils.init(getApplication());
        // 以下都不是必须的，根据需要自行选择
        OkHttpUtils.getInstance()//
//				.debug("OkHttpUtils") // 是否打开调试
                .setConnectTimeout(OkHttpUtils.DEFAULT_MILLISECONDS) // 全局的连接超时时间
                .setReadTimeOut(OkHttpUtils.DEFAULT_MILLISECONDS) // 全局的读取超时时间
                .setWriteTimeOut(OkHttpUtils.DEFAULT_MILLISECONDS);// 全局的写入超时时间
    }

    private void getIntentData() {
        Intent intent = getIntent();
        String action = intent.getAction();
        if (Intent.ACTION_VIEW.equals(action)) {
            Uri uri = intent.getData();
            if (uri != null) {
                mAppkey = uri.getQueryParameter("appKey");
                mPackageName = uri.getQueryParameter("pkgName");
                LogUtil.e("包名" + mPackageName);
//                PreferenceUtils.getInstance().save(Constant.PREFERENCE.MPKGNAME, mPackageName);
            }
        }
    }

    private void initView() {
        //TitleBar处理
        LinearLayout iv_top_left = (LinearLayout) findViewById(R.id.iv_top_left);
        iv_top_left.setVisibility(View.VISIBLE);
        iv_top_left.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tv_title_center = (TextView) findViewById(R.id.tv_title_center);
        tv_title_center.setText("统一认证");

        tv_title_right = (TextView) findViewById(R.id.tv_title_right);
        tv_title_right.setVisibility(View.GONE);
        tv_login_user_name = (TextView) findViewById(R.id.tv_login_user_name);
        tv_login_user_id = (TextView) findViewById(R.id.tv_login_user_id);
        ll_login_user = (LinearLayout) findViewById(R.id.ll_login_user);
        tv_title_right.setText("切换用户");
        btn_login = (Button) findViewById(R.id.btn_user_login);
        btn_user_logout = (Button) findViewById(R.id.btn_user_logout);
        iv_no_network = (ImageView) findViewById(R.id.iv_no_network);
        rl_no_network = (RelativeLayout) findViewById(R.id.rl_no_network);
    }

    private void initEvent() {
        btn_login.setOnClickListener(new DoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                toAuthLogin();
            }
        });
        tv_title_right.setOnClickListener(this);
        btn_user_logout.setOnClickListener(this);
        rl_no_network.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.tv_title_right) {
            isSwitcher = true;
            toSwitchUser();
        } else if (i == R.id.btn_user_logout) {
            toAuthLogOut(false);
        } else if (i == R.id.iv_top_left) {
            finish();
            Toast.makeText(getApplicationContext(), "认证取消", Toast.LENGTH_SHORT).show();
        } else if (i == R.id.rl_no_network) {
            rl_no_network.setVisibility(View.GONE);
            toAppAuthLogin();
        }
    }


    private void toAppAuthLogin() {
        appAuthDialog = DialogUtil.createLoadingDialog(this, "正在认证...");
        if (!NetUtil.isNetworkAvailable(this)) {
            appAuthDialog.dismiss();
            btn_login.setVisibility(View.GONE);
            tv_title_right.setVisibility(View.GONE);
            rl_no_network.setVisibility(View.VISIBLE);
            Toast.makeText(ARTAuthActivity.this, "当前无网络，请检查是否连接网络", Toast.LENGTH_SHORT).show();
            return;
        }
        UAManager.getInstance().init(getApplicationContext(), mAppkey);
        UAManager.getInstance().authLogin(this, mPackageName, new IAuthCallBack() {

            @Override
            public void onProgress(final String msg) {
                Log.d("progress", "authLogin onProgress " + msg);
//                appAuthDialog.setMessage(msg);
            }

            @Override
            public void onSuccess(AccessTokenInfo info) {
                Log.d("onSuccess", "authLoginError code:" + info.toString());
                appAuthDialog.dismiss();
                if (TextUtils.isEmpty(info.getStaffName())) {
                    DialogUtil.createAlertDialog(ARTAuthActivity.this,
                            "温馨提示", "验证失败,请重新验证");
                    finish();
                }
                mUserString = GsonUtil.getInstance().toJson(info);
                mAccessToken = info.getAccessToken();
                mTokenInfo = info;
                ll_login_user.setVisibility(View.VISIBLE);
                btn_user_logout.setVisibility(View.VISIBLE);
                tv_login_user_name.setText(info.getStaffName());
                tv_login_user_id.setText(info.getIdno());
                btn_login.setVisibility(View.VISIBLE);
            }

            @Override
            public void onError(int code, String msg) {
                appAuthDialog.dismiss();
                JsonDataResult result = new JsonDataResult<>();
                result.setRetCode(String.valueOf(IAuthCallBack.ERROR_AUTH_CANCEL));
                result.setRetMsg(msg);
                result.setRetCode(String.valueOf(code));
                Intent intent = new Intent();
                intent.putExtra(Constant.DATA, GsonUtil.objectToJson(result));
                setResult(AuthCode.RESULT_CODE, intent);
                Toast.makeText(ARTAuthActivity.this, msg, Toast.LENGTH_SHORT).show();
                finish();
                Log.d("error", "authLoginError code:" + code + " Msg:" + msg);
            }
        });
    }

    /**
     * 登出
     */

    /**
     * 退出登录
     */
    private void toAuthLogOut(final boolean switcher) {
        if (!NetUtil.isNetworkAvailable(this)) {
            Toast.makeText(ARTAuthActivity.this, "当前无网络，请检查是否连接网络", Toast.LENGTH_SHORT).show();
            return;
        }
        String json = GsonUtil.toLogoutJson();
        HttpUtil.post(json, new StoreStringCallBack(ARTAuthActivity.this) {
            @Override
            public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {
                super.onResponse(arg0, arg1, arg2, arg3);
                JsonDataRestult<Object> result = GsonUtil.decode(arg1, new TypeToken<JsonDataRestult<Object>>() {
                }.getType());

                if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
                    if (!switcher) {
                        Toast.makeText(getApplicationContext(), "登出成功", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        UAManager.getInstance().authLogout("");
        if (!switcher) {
            JsonDataResult result = new JsonDataResult();
            result.setRetCode(String.valueOf(IAuthCallBack.ERROR_USER_LOGOUT));
            result.setRetMsg("用户登出");
            Intent intent = new Intent();
            intent.putExtra(Constant.DATA, GsonUtil.objectToJson(result));
            setResult(AuthCode.RESULT_CODE, intent);
            finish();
        } else {
            UAManager.getInstance().switchLogin(mAccessToken, mPackageName, ARTAuthActivity.this,
                    new IAuthCallBack() {
                        @Override
                        public void onError(int code, String errorMsg) {
                            LogUtil.e(errorMsg);
                            Toast.makeText(ARTAuthActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onProgress(String msg) {
                        }

                        @Override
                        public void onSuccess(AccessTokenInfo info) {
                            if (TextUtils.isEmpty(info.getStaffName())) {
                                DialogUtil.createAlertDialog(ARTAuthActivity.this,
                                        "温馨提示", "验证失败,请重新验证");
                                finish();
                            }
                            mUserString = GsonUtil.getInstance().toJson(info);
                            mAccessToken = info.getAccessToken();
                            ll_login_user.setVisibility(View.VISIBLE);
                            tv_login_user_name.setText(info.getStaffName());
                            tv_login_user_id.setText(info.getIdno());
                            btn_login.setVisibility(View.VISIBLE);
                        }
                    });
        }
    }

    /**
     * 切换用户
     */
    private void toSwitchUser() {
//        tv_title_right.setVisibility(View.GONE);
//        ll_login_user.setVisibility(View.GONE);
//        btn_user_logout.setVisibility(View.GONE);
        toAuthLogOut(true);
    }

    private void toAuthLogin() {
        mLoadingDialog = DialogUtil.createLoadingDialog(this, "正在登陆...");
        UAManager.getInstance().getStaffInfo(mAccessToken, new OperationCallBack() {

            @Override
            public void onSuccess(String json) {
                mLoadingDialog.dismiss();
                Staff staffInfo = (Staff) GsonUtil.fromJson(json, Staff.class);
                if (staffInfo != null && mTokenInfo != null) {
                    staffInfo.setUuid(mTokenInfo.getUuid());
                    staffInfo.setImei(mTokenInfo.getImei());
                    staffInfo.setUid(mTokenInfo.getUid());
                    staffInfo.setTfCa(mTokenInfo.getTfCa());
                    staffInfo.setTfNumber(mTokenInfo.getTfNumber());
                    staffInfo.setNetType(mTokenInfo.getNetType());
                }
                JsonDataResult<Staff> result = new JsonDataResult<Staff>();
                result.setRetCode("0000");
                result.setRetMsg("登陆成功");
                result.setData(staffInfo);
                Intent intent = new Intent();
                LogUtil.e("用户信息" + staffInfo.toString());
                intent.putExtra(Constant.DATA, GsonUtil.objectToJson(result));
                setResult(AuthCode.RESULT_CODE, intent);
                finish();
            }

            @Override
            public void onError(int code, String errorMsg) {
                mLoadingDialog.dismiss();
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (proDialog != null) {
            proDialog.dismiss();
        }
        if (mLogoutDialog != null) {
            mLogoutDialog.dismiss();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UAManager.getInstance().decodeResult(requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        Toast.makeText(getApplicationContext(), "认证取消", Toast.LENGTH_SHORT).show();
    }
}

